<?php
namespace app\admin\model;

use Elasticsearch\ClientBuilder;
/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
class BaseModel{
    public $client;
    public $body;
    public $index;
    public $type;
    public function __construct() {
        vendor ('autoload');
        $config=[[
            'user'=>'elastic',
            'pass'=>'oFgK&+UZVTo?xj3&G9@p',
            'host'=>'123.207.85.206',
            'scheme' => 'http',
            'port'=>'9200',
        ],];
        $client = ClientBuilder::create()->setHosts($config)->build();
        $this->client=$client;
        return $this->client;
    }

    public function SetBody($body){
        $this->body=json_encode($body);
        return $this;
    }

    public function setIndex($index){
        $this->index=$index;
        return $this;
    }

    public function search(){
        if(!$this->index){
            validate_error("未设置索引类型");
        }
        $params = [
            'index'  => $this->index,
            'body' => $this->body,
            'client' => [ 'ignore' => 404 ] 
        ];
        $result=$this->client->search($params);
        if(!is_array($result)){
                $result= json_decode($result,true);
        }
        if(isset($result['aggregations'])){
            return $result['aggregations'];
        }else{
            return $result;
        }
    }
    public function count(){
        if(!$this->index){
            validate_error("未设置索引类型");
        }
        $params = [
            'index'  => $this->index,
        ];
        return $this->client->count($params);
    }
}

